﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using Citrix.Cmp;
using System.Windows;

namespace Citrix.XaAdminMobile.ViewModel
{
    /// <summary>
    /// Used to display a loading status. This is the v-m for the <see cref="LoadingView"/>.
    /// </summary>
    /// <remarks>
    /// Not thread safe, use from UI thread only.
    /// </remarks>
    class LoadingViewModel : INotifyPropertyChanged
    {
        /// <summary>
        /// A delegate which returns whether we are currently loading.
        /// </summary>
        private readonly Func<bool> isLoadingDelegate;

        /// <summary>
        /// Initialisation ctor.
        /// </summary>
        /// <param name="checkIfLoading">The loading delegate returns whether this loading
        /// status should be displayed.</param>
        /// <exception cref="ArgumentNullException">Thrown if any arg is null.</exception>
        public LoadingViewModel(Func<bool> checkIfLoading)
        {
            if (null == checkIfLoading)
            {
                throw new ArgumentNullException("checkIfLoading");
            }

            this.isLoadingDelegate = checkIfLoading;
        }

        /// <summary>
        /// True if loading, false if not.
        /// </summary>
        public bool IsLoading
        {
            get { return this.isLoadingDelegate(); }
        }

        /// <summary>
        /// Returns a visibility to bind to the visbility of the loading control.
        /// </summary>
        public Visibility LoadingVisibility
        {
            get { return this.isLoadingDelegate() ? Visibility.Visible : Visibility.Collapsed; }
        }

        /// <summary>
        /// Called when the visbility of this control has changed.
        /// </summary>
        public void NotifyChanged()
        {
            OnPropertyChanged("IsLoading");
            OnPropertyChanged("LoadingVisibility");
        }

        #region INotifyPropertyChanged Members

        /// <summary>
        /// Fired whenever a public property changes.
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// Fires the property change event. Maybe called from any thread - we always fire the
        /// event on the main UI thread.
        /// </summary>
        /// <param name="propertyName">The name of the property that changed.</param>
        private void OnPropertyChanged(string propertyName)
        {
            NotifyHelper.VerifyProperty(propertyName, this);
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged.Raise(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        #endregion // INotifyPropertyChanged Members
    }
}
